<?php


namespace app\api\library\order\refundNotify;

use app\api\model\MallCollage;
use app\api\model\MallGoods;
use app\api\model\MallOrder;
use app\api\model\MallTradeRecordLog;
use app\api\model\MallUser;
use think\facade\Db;
use think\Exception;
use think\facade\Config;
use think\facade\Log;
use Yansongda\Pay\Pay;

class V
{
    public static function run()
    {
        Log::write('WeChatNotify1');
        //配置
        $config = Config::get('payConfig');
        //初始化
        Pay::config($config);
        
        try {
            $data = Pay::wechat()->callback();
            Log::write($data->all());
            $data = $data->toArray();
            $data = $data[ 'resource' ][ 'ciphertext' ];
            Log::write($data);
            //验证返回状态
            if ($data[ 'refund_status' ] != 'SUCCESS') {
                $msg = "微信支付异步回调出现错误" . "  return_msg:" . $data[ 'return_msg' ];
                _throwNewException($msg);
            }
//            if ($data->result_code == 'FAIL') {
//                $msg = "微信支付异步回调出现错误" . '	err_code:' . $data->err_code . "  err_code_des:" . $data->err_code_des;
//                _throwNewException($msg);
//            }
            
            //处理微信数据
            [$dataArr, $order] = self::handleWechatData($data);
            //验证通过，封装更新订单状态方法
            self::afterPay($dataArr, $order);
            
            return Pay::wechat()->success();
        } catch (\Exception $e) {
            
            Log::write($e);
            
            exit("fail");
        }
    }
    
    /**
     * 处理微信数据
     * @param $data
     * @return array
     * @throws Exception
     */
    public static function handleWechatData($data)
    : array
    {
        //订单编号
        $orderNo = $data[ 'out_trade_no' ];
        //付款金额 单位元=>分
        $payPrice = (int) $data[ 'amount' ][ 'payer_total' ];
        //获取订单 包含验证订单号、付款金额
        $order = MallOrder::where('order_no', $orderNo)->find()->toArray();
        Log::write($order);
        //取出所有数据
        $dataArr = [
            //三方订单编号trade_no
            'trade_no'     => $data[ 'transaction_id' ],
            //支付方式pay_type 1.支付宝 2.微信
            'pay_mode'     => 2,
            //付款金额 pay_price 单位为分
            'refund_price' => $payPrice,
            //支付时间
            //            'pay_time'  => date('Y-m-d H:i:s', strtotime($data->time_end)),
        ];
        return [$dataArr, $order];
    }
    
    /**
     * 付款后
     * @param $dataArr
     * @param $diagnoseOrder
     * @param $payMode
     * @throws \think\Exception
     */
    public static function afterPay($dataArr, $order)
    {
        //取出订单id
        $orderId = $order[ 'id' ];
        //订单编号
        $orderNo = $order[ 'order_no' ];
        //用户ID
        $userId = $order[ 'user_id' ];
        //余额支付部分
        $payBalance = $order[ 'pay_balance' ];
        //判断状态
        if ( !in_array($order[ 'order_status' ], [70, 40])) {
            //多方支付异步重复 记录日志
            $msg = 'pay notify repeat: ' . $orderNo;
            Log::warning($msg);
            exit("fail");
        }
        $balance = MallUser::where('id', $userId)->value('balance');
        try {
            //开启事务
            Db::startTrans();
            $failure_reward = MallCollage::where('collage_id', $order[ 'collage_id' ])->value('failure_reward');
            //修改订单状态
            $modOrder = ['refund_status' => 40];
            if ($order[ 'order_status' ] == 70) {
                $type1 = 10;
                $type2 = 11;
            } else {
                //添加失败奖励
                $type1 = 12;
                $type2 = 13;
            }
            //添加交易记录
            MallTradeRecordLog::addRecord($userId, $orderId, $dataArr[ 'refund_price' ], 0, $type1);
            if ($payBalance > 0) {
                $addBalance = $balance + $payBalance;
                //加上余额
                if (false === MallUser::where([['id', '=', $userId]])->update(['balance' => $addBalance])) {
                    _throwNewException('订单支付失败3');
                }
                //添加交易记录
                MallTradeRecordLog::addRecord($userId, $orderId, $payBalance, $addBalance, $type2);
            }
            if (false === MallOrder::where([['id', '=', $orderId]])->update($modOrder)) {
                _throwNewException('订单支付失败1');
            }
            // 提交事务
            Db::commit();
            //记录支付后，修改订单状态成功
            Log::Info('pay notify success:' . $orderNo);
        } catch (Exception $e) {
            
            Log::write($e);
            // 回滚事务
            Db::rollback();
            throw new \think\Exception("orderNo:$orderNo " . $e->getMessage());
        }
    }
}